<template>
  <el-menu
    :default-active="activeIndex"
    class="nav-menu"
    mode="horizontal"
    router
    background-color="#ffffff"
    text-color="#303133"
    active-text-color="#409EFF"
  >
    <el-menu-item index="/">
      <el-icon><HomeFilled /></el-icon>
      首页
    </el-menu-item>
    
    <el-menu-item index="/qa">
      <el-icon><QuestionFilled /></el-icon>
      问答
    </el-menu-item>

    <div class="flex-grow" />

    <template v-if="!isAuthenticated">
      <el-menu-item index="/login">
        <el-icon><User /></el-icon>
        登录
      </el-menu-item>
      <el-menu-item index="/register">
        <el-icon><UserFilled /></el-icon>
        注册
      </el-menu-item>
    </template>

    <template v-else>
      <el-menu-item index="/write">
        <el-icon><EditPen /></el-icon>
        写文章
      </el-menu-item>
      <el-sub-menu index="user">
        <template #title>
          <el-icon><User /></el-icon>
          {{ currentUser?.username }}
        </template>
        <el-menu-item @click="handleLogout">
          <el-icon><SwitchButton /></el-icon>
          退出登录
        </el-menu-item>
      </el-sub-menu>
    </template>
  </el-menu>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import {
  HomeFilled,
  QuestionFilled,
  User,
  UserFilled,
  EditPen,
  SwitchButton
} from '@element-plus/icons-vue'

export default {
  name: 'NavBar',
  components: {
    HomeFilled,
    QuestionFilled,
    User,
    UserFilled,
    EditPen,
    SwitchButton
  },
  setup() {
    const store = useStore()
    const router = useRouter()
    const route = useRoute()

    const isAuthenticated = computed(() => store.getters.isAuthenticated)
    const currentUser = computed(() => store.getters.currentUser)
    const activeIndex = computed(() => route.path)

    const handleLogout = async () => {
      try {
        await store.dispatch('logout')
        router.push('/login')
      } catch (error) {
        console.error('退出登录失败：', error)
      }
    }

    return {
      isAuthenticated,
      currentUser,
      activeIndex,
      handleLogout
    }
  }
}
</script>

<style scoped>
.nav-menu {
  border-bottom: solid 1px #e6e6e6;
  padding: 0 20px;
}

.flex-grow {
  flex-grow: 1;
}

:deep(.el-sub-menu__title) {
  display: flex;
  align-items: center;
}

:deep(.el-menu--horizontal > .el-menu-item),
:deep(.el-menu--horizontal > .el-sub-menu .el-sub-menu__title) {
  height: 60px;
  line-height: 60px;
}

.el-icon {
  margin-right: 5px;
}
</style> 